package com.android.citynetworkpin;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.citynetworkpin.activity.BaseObject;
import com.android.citynetworkpin.activity.CityChoose;
import com.android.citynetworkpin.activity.mine.LoginActivity;
import com.android.citynetworkpin.app.BaseActivity;
import com.android.citynetworkpin.enums.EJumpStatus;
import com.android.citynetworkpin.fragment.Fragment1;
import com.android.citynetworkpin.fragment.Fragment4;
import com.android.citynetworkpin.fragment.Fragment5;
import com.android.citynetworkpin.fragment.Fragment_NewProduct;
import com.android.citynetworkpin.fragment.member.Fragment_SeaAmoy;
import com.android.citynetworkpin.model.group.CitySetData;
import com.android.citynetworkpin.model.group.CitySetDataCallback;
import com.android.citynetworkpin.model.member.MemberInfoData;
import com.android.citynetworkpin.model.member.MemberInfoDataCallback;
import com.android.citynetworkpin.pojo.BannerUintPojo;
import com.android.citynetworkpin.utils.ConstantsUrl;
import com.android.citynetworkpin.utils.HttpUtils;
import com.android.citynetworkpin.utils.JumpUtils;
import com.android.citynetworkpin.utils.LoginState;
import com.android.citynetworkpin.utils.ObjectUtils;
import com.android.citynetworkpin.utils.update.DownloadCallback;
import com.android.citynetworkpin.utils.update.UpVersion;
import com.android.citynetworkpin.utils.update.UpVersionDialog;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;

/**
 * 主页
 */

public class MainActivity extends BaseActivity {

    private int index;
    private int currentTabIndex;
    private ImageView[] imagebuttons;
    private TextView[] textviews;
    private boolean isExit;
    private MainActivity mcontext;
    Handler mHandler = new Handler();
    private LocationClientOption option = new LocationClientOption();
    private MyLocationListener myLocationListener = new MyLocationListener();
    private String locationcity;
    private String returncity;
    private List<String> permissionList;
    private LocationClient mLocationClient;
    private String return_type;
    private String nextName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mcontext = MainActivity.this;
        initUI();
        toJump();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        toJump();
    }

    private void toJump() {
        String return_type = getIntent().getStringExtra("return_type");
        String title = getIntent().getStringExtra("title");
        if (!TextUtils.isEmpty(return_type)) {
            BannerUintPojo Apojo = new BannerUintPojo();
            Apojo.return_type = return_type;
            Apojo.title = title;
            JumpUtils.jumpToEveryWhere(mcontext, Apojo, null);
        }
    }

    public void initUI() {
        changeFragment();
        setTabSelect(0);
        Update();
        if (LoginState.getInstance().isLogin(mcontext)) {
            upUserData();
        }
        mLocationClient = new LocationClient(this.getApplicationContext());
        mLocationClient.registerLocationListener(myLocationListener);
        permissionList = new ArrayList<String>();
    }

    private void upUserData() {
        boolean networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        if (networkConnected) {
            String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORDINGDANGNUM;
            String getid = LoginState.getInstance().getid(mcontext);
            String getpd = LoginState.getInstance().getpd(mcontext);
            HashMap<String, String> header = new HashMap<>();
            header.put("UID", getid);
            header.put("UPSW", getpd);
            HttpUtils.get(address, header, null, new MemberInfoDataCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(MemberInfoData response, int id) {
                    MemberInfoData.DataBean data = response.getData();
                    if (response.getCode() == 0 && data != null) {
                        MemberInfoData.DataBean.MemberBean member = data.getMember();
                        if (member != null) {
                            SharedPreferences sp = mcontext.getSharedPreferences(ConstantsUrl.USERDATA, 0);
                            SharedPreferences.Editor edit = sp.edit();
                            edit.putString(ConstantsUrl.USERDATA_NAME, member.getNickname());
                            edit.putString(ConstantsUrl.USERDATA_AVATAR, member.getPhoto());
                            edit.putString(ConstantsUrl.USERDATA_UID, member.getMid());
                            edit.putString(ConstantsUrl.USERDATA_ZONE, member.getZone());
                            edit.putString(ConstantsUrl.USERDATA_CITY, member.getCity());
                            edit.commit();
                        }
                    }
                }
            });
        }
    }

    private void Update() {
        String address = ConstantsUrl.domain + ConstantsUrl.MAIN_UPDATE_VERSION;
        HttpUtils.get(address, null, null, new DownloadCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(UpVersion response, int id) {
                if (response == null) {
                    return;
                }
                UpVersion.DataBean data = response.getData();
                if (response.getCode() == 0 && data != null) {
                    if (ObjectUtils.getVersionCode(MainActivity.this) < Integer.parseInt(data.getName())) {
                        UpVersionDialog upVersionDialog = new UpVersionDialog();
                        upVersionDialog.show(mcontext.getFragmentManager(), "upVersionDialog");
                    }
                }
            }
        });
    }


    private DataChange dataChange;

    public void setData(DataChange dataChange) {
        this.dataChange = dataChange;
    }

    public interface DataChange {
        void setDataChange(int curr);
    }

    private void ONscroll(int curr) {
        if (dataChange != null) {
            dataChange.setDataChange(curr);
        }
    }

    private Fragment Fragment1, Fragment2, Fragment3, Fragment4, Fragment5;

    public void setTabSelect(int i) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        switch (i) {
            case 0:
                Fragment1 = manager.findFragmentByTag("TAG1");
                hideTab(transaction);
                if (Fragment1 == null) {
                    Fragment1 = new Fragment1();
                    transaction.add(R.id.fragment_container, Fragment1, "TAG1");
                } else {
                    transaction.show(Fragment1);
                }
                break;
            case 1:
                Fragment2 = manager.findFragmentByTag("TAG2");
                hideTab(transaction);
                if (Fragment2 == null) {
                    Fragment2 = new Fragment_NewProduct();
                    transaction.add(com.android.citynetworkpin.R.id.fragment_container, Fragment2, "TAG2");
                } else {
                    transaction.show(Fragment2);
                }
                break;
            case 2:
                Fragment3 = manager.findFragmentByTag("TAG3");
                hideTab(transaction);
                if (Fragment3 == null) {
                    Fragment3 = new Fragment_SeaAmoy();
                    transaction.add(R.id.fragment_container, Fragment3, "TAG3");
                } else {
                    transaction.show(Fragment3);
                }
                break;
            case 3:
                Fragment4 = manager.findFragmentByTag("TAG4");
                hideTab(transaction);
                if (Fragment4 == null) {
                    Fragment4 = new Fragment4();
                    transaction.add(R.id.fragment_container, Fragment4, "TAG4");
                } else {
                    transaction.show(Fragment4);
                }
                break;
//                    Fragment4 = manager.findFragmentByTag("TAG4");
//                    hideTab(transaction);
//
//                if (LoginState.getInstance().isLogin(mcontext)) {
//                    if (Fragment4 == null) {
//                        if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED)
//                        {
//                         permissionList.clear();
//                            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
//                        }
//                        String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
//                        MyLog.e("oonzone",zone);
//                        if(zone.equals("")||zone==null) {
//
//                            if(!permissionList.isEmpty())
//                            {
//                                String [] permissions = permissionList.toArray(new String[permissionList.size()]);
//                                ActivityCompat.requestPermissions(MainActivity.this,permissions,1);
//                            }
//                            else
//                            {
//                                requestLocation();
//                            }
//
//                        }
//                        else
//                            {
//                                Fragment4 = new Fragment_SameCity_Service();
//                                transaction.add(R.id.fragment_container, Fragment4, "TAG4");
//                        }
//                    } else {
//                        transaction.show(Fragment4);
//                    }
//               }
//                else
//            {
//
//                int requestCode = 2;
//                startActivityForResult(new Intent(mcontext, LoginActivity.class),requestCode);
//
//            }
//                break;
            case 4:
                Fragment5 = manager.findFragmentByTag("TAG5");
                hideTab(transaction);
                if (Fragment5 == null) {
                    Fragment5 = new Fragment5();
                    transaction.add(R.id.fragment_container, Fragment5, "TAG5");
                } else {
                    ONscroll(1);
                    transaction.show(Fragment5);
                }
                break;
        }
        transaction.commitAllowingStateLoss();

    }

    private void hideTab(FragmentTransaction transaction) {
        if (Fragment1 != null) {
            transaction.hide(Fragment1);
        }
        if (Fragment2 != null) {
            transaction.hide(Fragment2);
        }
        if (Fragment3 != null) {
            transaction.hide(Fragment3);
        }
        if (Fragment4 != null) {
            transaction.hide(Fragment4);
        }
        if (Fragment5 != null) {
            transaction.hide(Fragment5);
        }
    }

    private void changeFragment() {
        imagebuttons = new ImageView[5];
        imagebuttons[0] = (ImageView) findViewById(com.android.citynetworkpin.R.id.mian_tab_img_1);
        imagebuttons[1] = (ImageView) findViewById(com.android.citynetworkpin.R.id.mian_tab_img_2);
        imagebuttons[2] = (ImageView) findViewById(com.android.citynetworkpin.R.id.mian_tab_img_3);
        imagebuttons[3] = (ImageView) findViewById(com.android.citynetworkpin.R.id.mian_tab_img_4);
        imagebuttons[4] = (ImageView) findViewById(com.android.citynetworkpin.R.id.mian_tab_img_5);
        imagebuttons[0].setSelected(true);
        textviews = new TextView[5];
        textviews[0] = (TextView) findViewById(com.android.citynetworkpin.R.id.mian_tab_tv_1);
        textviews[1] = (TextView) findViewById(com.android.citynetworkpin.R.id.mian_tab_tv_2);
        textviews[2] = (TextView) findViewById(com.android.citynetworkpin.R.id.mian_tab_tv_3);
        textviews[3] = (TextView) findViewById(com.android.citynetworkpin.R.id.mian_tab_tv_4);
        textviews[4] = (TextView) findViewById(com.android.citynetworkpin.R.id.mian_tab_tv_5);
        textviews[0].setTextColor(0xFFFF2741);
    }

    //改变主界面的fragment
    public void ChangeMainFragment(int type) {
        index = type;
        imagebuttons[currentTabIndex].setSelected(false);
        imagebuttons[index].setSelected(true);
        textviews[currentTabIndex].setTextColor(0xFF333333);
        textviews[index].setTextColor(0xFFFF2741);
        currentTabIndex = index;
        setTabSelect(type);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 1:
                String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
                if (!zone.equals("")) {
                    index = 3;
                    setTabSelect(3);
                } else {
                    index = 0;
                    setTabSelect(0);
                }
                imagebuttons[currentTabIndex].setSelected(false);
                imagebuttons[index].setSelected(true);
                textviews[currentTabIndex].setTextColor(0xFF333333);
                textviews[index].setTextColor(0xFFFF2741);
                currentTabIndex = index;
                break;
            case 2:
                index = 0;
                imagebuttons[currentTabIndex].setSelected(false);
                imagebuttons[index].setSelected(true);
                textviews[currentTabIndex].setTextColor(0xFF333333);
                textviews[index].setTextColor(0xFFFF2741);
                currentTabIndex = index;
                setTabSelect(0);
                break;

        }
    }

    public void onTabClicked(View v) {
        switch (v.getId()) {
            case com.android.citynetworkpin.R.id.mian_tab_rl_1:
                index = 0;
                setTabSelect(0);
                break;
            case com.android.citynetworkpin.R.id.mian_tab_rl_2:
                index = 1;
                setTabSelect(1);
                break;
            case com.android.citynetworkpin.R.id.mian_tab_rl_3:
                index = 2;
                setTabSelect(2);
                break;
            case com.android.citynetworkpin.R.id.mian_tab_rl_4:

                index = 3;
                setTabSelect(3);
                break;
            case com.android.citynetworkpin.R.id.mian_tab_rl_5:
                index = 4;
                setTabSelect(4);
                break;
        }
        imagebuttons[currentTabIndex].setSelected(false);
        imagebuttons[index].setSelected(true);
        textviews[currentTabIndex].setTextColor(0xFF333333);
        textviews[index].setTextColor(0xFFFF2741);
        currentTabIndex = index;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isExit) {
                SharedPreferences sp = getSharedPreferences("time", 0);
                SharedPreferences.Editor edit = sp.edit();
                edit.clear();
                edit.commit();
                System.exit(0);
            } else {
                ObjectUtils.toast(mcontext, "再按一次就可以退出了");
                isExit = true;
            }
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 2000);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //同城商品定位逻辑
    public void requestLocation() {
        option.setIsNeedLocationDescribe(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        //option.setScanSpan(3000);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestcode, String[] permissions, int[] grantResults) {
        switch (requestcode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this, "尚不能应用定位", Toast.LENGTH_LONG).show();
                            int requestCode = 1;
                            startActivityForResult(new Intent(mcontext, CityChoose.class), requestCode);
                            return;
                        }
                    }
                    requestLocation();
                } else {
                    Toast.makeText(this, "发生未知错误", Toast.LENGTH_LONG).show();
                }
                break;
            default:
                break;
        }
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            locationcity = location.getCity();
            PostCitySet();
        }
    }

    //同城商品定位逻辑
    private void PostCitySet() {
        String address = ConstantsUrl.domain + ConstantsUrl.CITYLOCATE;
        String getid = LoginState.getInstance().getid(mcontext);
        String getpd = LoginState.getInstance().getpd(mcontext);
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();
        header.put("UID", getid);
        header.put("UPSW", getpd);
        map.put("city", locationcity + "");

        HttpUtils.post(address, header, map, new CitySetDataCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                ObjectUtils.toast(mcontext, "定位失败，请稍后重试");
            }

            @Override
            public void onResponse(CitySetData response, int id) {
                if (response == null) {
                    return;
                }
                CitySetData.DataBean data = response.getData();
                if (response.getCode() == 0 && data != null) {
                    String zone = data.getZone();
                    returncity = data.getCity();
                    SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
                    if (sp != null) {
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putString(ConstantsUrl.USERDATA_ZONE, zone);
                        edit.putString(ConstantsUrl.USERDATA_CITY, returncity);
                        edit.commit();
                    }
//                    if (nextName != null) {
//                        if (nextName.equals("同城商品") || nextName.equals("同城") || nextName.equals("同城新零售")) {
//                            toObject(nextName, "");
//                        }
//                    }
                    if (return_type != null) {
                        if (return_type.equals(EJumpStatus.EnumSameCity.getRegmatch())) {
                            toObject(nextName, "");
                        }
                    }
                } else {
                    ObjectUtils.toast(mcontext, "定位失败，请稍后重试");
                }
            }
        });
    }

    public boolean isLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.clear();
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        String zone = LoginState.getInstance().getUserInfo(mcontext, 2);
        if (TextUtils.isEmpty(zone) || zone.equals("0")) {
            if (!permissionList.isEmpty()) {
                String[] permissions = permissionList.toArray(new String[permissionList.size()]);
                ActivityCompat.requestPermissions(this, permissions, 1);
            } else {
                requestLocation();
            }
            return false;
        } else {
            return true;
        }
    }

    public void JumptoSameCity(String return_type, String nextName) {
        this.return_type = return_type;
        this.nextName = nextName;
        if (LoginState.getInstance().isLogin(mcontext)) {
//            requestLocation();
            boolean location = isLocation();
            if (location) {
                toObject(nextName, "");
            }
        } else {
            startActivity(new Intent(mcontext, LoginActivity.class));
        }
    }

    private void toObject(String title, String id) {
        Intent intent = new Intent(mcontext, BaseObject.class);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_TITLE, title);
        intent.putExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_OBJEXT_SORT_NEED_ID, id);
        intent.putExtra(ConstantsUrl.INTENT_KEY.RETURN_TYPE, return_type);
        startActivity(intent);
    }
}
